import paho.mqtt.client as mqtt
import json
import time
import uuid

# MQTT配置信息
mqttConfig = {
    'serverAddress': '82.157.22.162',
    'wsPort': 8083,
    'mqttPort': 1883,
    'clientId': '',  # 留空将自动生成
    'username': '',
    'password': '',
    'keepalive': 60,
    'topic': 'maixcam_cmd',
    'topdata': 'maixcam_data'
}

# 生成唯一的客户端ID（如果未提供）
if not mqttConfig['clientId']:
    mqttConfig['clientId'] = f"maixcam_{str(uuid.uuid4())[:8]}"

class MaixCAMProMQTT:
    def __init__(self):
        self.client = mqtt.Client(client_id=mqttConfig['clientId'])
        self.client.username_pw_set(mqttConfig['username'], mqttConfig['password'])
        
        # 设置回调函数
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect
    
    def on_connect(self, client, userdata, flags, rc):
        """连接成功回调"""
        if rc == 0:
            print(f"✅ 成功连接到MQTT服务器: {mqttConfig['serverAddress']}:{mqttConfig['mqttPort']}")
            # 订阅命令主题
            client.subscribe(mqttConfig['topic'])
            print(f"✅ 已订阅主题: {mqttConfig['topic']}")
        else:
            print(f"❌ 连接失败，错误代码: {rc}")
    
    def on_message(self, client, userdata, msg):
        """收到消息回调"""
        try:
            topic = msg.topic
            payload = msg.payload.decode('utf-8')
            print(f"📥 收到消息 - 主题: {topic}, 内容: {payload}")
            
            # 尝试解析JSON格式的消息
            try:
                data = json.loads(payload)
                print(f"📋 解析后的JSON数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
                
                # 检查是否为LED控制命令
                if data.get('type') == 'led':
                    print(f"✨ 收到LED控制命令，准备控制闪光灯...")
                    # 执行闪光灯控制
                    self.control_flashlight()
                else:
                    print(f"ℹ️ 收到非LED控制命令，类型: {data.get('type')}")
                    
            except json.JSONDecodeError:
                print("⚠️ 消息不是有效的JSON格式")
        except Exception as e:
            print(f"❌ 处理消息时出错: {e}")
    
    def control_flashlight(self):
        """控制闪光灯闪烁一秒钟"""
        try:
            print("💡 闪光灯开启")
            
            # 这里添加实际控制闪光灯的代码
            # 由于MaixCAM设备的具体API可能不同，这里提供几种可能的实现方式
            
            # 方式1: 假设使用gpio库控制LED
            # import gpio
            # gpio.set_mode(flashlight_pin, gpio.OUTPUT)
            # gpio.write(flashlight_pin, gpio.HIGH)
            
            # 方式2: 假设使用MaixPy的API
            # from maix import gpio
            # flash_led = gpio.gpio(flashlight_pin, gpio.OUT)
            # flash_led.set_value(1)
            
            # 方式3: 如果设备提供了特定的API
            # camera.set_flashlight(True)
            
            # 模拟闪光灯开启1秒钟
            time.sleep(1)
            
            print("💡 闪光灯关闭")
            
            # 关闭闪光灯的代码（与开启相对应）
            # gpio.write(flashlight_pin, gpio.LOW)
            # 或 flash_led.set_value(0)
            # 或 camera.set_flashlight(False)
            
            # 闪光灯控制完成后，发送MQTT消息
            self.send_flash_complete_message()
            
        except Exception as e:
            print(f"❌ 控制闪光灯时出错: {e}")
            print("💡 请注意: 您可能需要根据MaixCAM设备的具体API调整闪光灯控制代码")
    
    def send_flash_complete_message(self):
        """发送闪光灯完成消息到MQTT服务器"""
        try:
            message = {
                "type": "flashlight_status",
                "status": "completed",
                "timestamp": int(time.time() * 1000)
            }
            
            # 发布消息到数据主题
            result = self.client.publish(mqttConfig['topdata'], json.dumps(message, ensure_ascii=False), qos=1)
            if result.rc == mqtt.MQTT_ERR_SUCCESS:
                print(f"📤 成功发送闪光灯完成消息到主题 {mqttConfig['topdata']}")
            else:
                print(f"❌ 发送闪光灯完成消息失败，错误代码: {result.rc}")
        except Exception as e:
            print(f"❌ 发送闪光灯完成消息时出错: {e}")
    
    def on_disconnect(self, client, userdata, rc):
        """断开连接回调"""
        if rc != 0:
            print(f"❌ 意外断开连接，错误代码: {rc}")
        else:
            print("👋 已断开与MQTT服务器的连接")
    
    def connect(self):
        """连接到MQTT服务器"""
        try:
            print(f"🔄 正在连接到MQTT服务器: {mqttConfig['serverAddress']}:{mqttConfig['mqttPort']}...")
            self.client.connect(mqttConfig['serverAddress'], mqttConfig['mqttPort'], mqttConfig['keepalive'])
            return True
        except Exception as e:
            print(f"❌ 连接MQTT服务器失败: {e}")
            return False
    
    def publish(self, message):
        """发布消息到命令主题"""
        try:
            # 如果消息是字典，转换为JSON字符串
            if isinstance(message, dict):
                message = json.dumps(message)
            
            result = self.client.publish(mqttConfig['topic'], message, qos=1)
            if result.rc == mqtt.MQTT_ERR_SUCCESS:
                print(f"📤 成功发布消息到主题 {mqttConfig['topic']}: {message}")
                return True
            else:
                print(f"❌ 发布消息失败，错误代码: {result.rc}")
                return False
        except Exception as e:
            print(f"❌ 发布消息时出错: {e}")
            return False
    
    def start(self):
        """启动MQTT客户端循环"""
        try:
            self.client.loop_start()
            print(f"▶️ MQTT客户端循环已启动")
        except Exception as e:
            print(f"❌ 启动MQTT客户端循环失败: {e}")
    
    def stop(self):
        """停止MQTT客户端循环"""
        try:
            self.client.loop_stop()
            self.client.disconnect()
            print(f"⏹️ MQTT客户端已停止")
        except Exception as e:
            print(f"❌ 停止MQTT客户端失败: {e}")

def send_maixcam_command(mqtt_client, command_type, params=None):
    """发送命令到MaixCAM设备"""
    if params is None:
        params = {}
    
    command = {
        'type': command_type,
        'params': params,
        'timestamp': int(time.time() * 1000)  # 毫秒时间戳
    }
    
    return mqtt_client.publish(command)

def main():
    # 创建MaixCAM Pro MQTT客户端实例
    mqtt_client = MaixCAMProMQTT()
    
    try:
        # 连接到MQTT服务器
        if not mqtt_client.connect():
            return
        
        # 启动MQTT客户端循环
        mqtt_client.start()
        
        # 等待连接稳定
        time.sleep(2)
        
        print("\n📱 MaixCAM Pro MQTT客户端已启动！")
        print("🎯 正在接收 maixcam_cmd 主题的指令...")
        print("\n按Ctrl+C退出...\n")
        
        # 保持程序运行，等待接收指令
        while True:
            time.sleep(1)
    
    except KeyboardInterrupt:
        print("\n👋 用户中断程序")
    finally:
        # 停止MQTT客户端
        mqtt_client.stop()

if __name__ == "__main__":
    main()
